/**********************************
*@brief:  与web端建立websocket通信连接
*@version: v.0
*@date: 2021/03/14
***********************************/

package hanlder

import (
	"fmt"
	"net/http"
	"sync"
	"time"

	"github.com/gorilla/websocket"
	"github.com/sirupsen/logrus"
)

var WsMsg string
var mutux sync.Mutex
var UP = websocket.Upgrader{
	ReadBufferSize:  1024,
	WriteBufferSize: 1024,
	//HandshakeTimeout: 30 * time.Second,
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
}

// 创建websocket句柄
func (pv *webSocketHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	conn, err := UP.Upgrade(w, r, nil)
	if err != nil {
		fmt.Println(err)
		return
	}
	for {
		select {
		case stat := <-GlobalLimit:
			if stat == 5 {
				mutux.Lock()
				err := conn.WriteMessage(websocket.TextMessage, []byte(WsMsg))
				logrus.Info("websocket 发送的数据  Message:", WsMsg)
				if err != nil {
					fmt.Println("收到消息，退出程序！")
					mutux.Unlock()
					return
				}
				mutux.Unlock()
				time.Sleep(5 * time.Millisecond)
			}

		}

	}
	defer func() {
		conn.Close()
	}()
}
